int A= 12, B= -456;

DecimalFormat numform = new DecimalFormat("###0.0###"); 

System.out.println( "A = " + numform.format(A) );
System.out.println( "B = " + numform.format(B) );

Answer:

A = 12.0
B = -456.0

The fragment writes a string that includes a fractional part, ".0" even though the numbers are ints. This might mislead someone into thinking the numbers are accurate to tenths. It might be better to use a format code that does not contain a decimal point.

Formatting Symbols

Here is a table of characters that may be used in number format patterns. The first six characters have already been discussed. The others will not be discussed, but are included so that you know they exist. Avoid using them without further study.

Symbol Location Meaning
0 Number Digit
# Number Digit, leading a trailing zeros removed
. Number Decimal separator
- Number Minus sign
, Number Grouping separator
$ Prefix or suffix Currency sign, replaced by currency symbol.
E Number Separates mantissa and exponent in scientific notation.
; Between Patterns Separates positive and negative subpatterns
% Prefix or suffix Multiply by 100 and show as percentage
$ Prefix or suffix Currency sign, replaced by currency symbol.
' Prefix or suffix Used to quote special characters in a prefix or suffix.

There are other features of DecimalFormat not discussed in this chapter. For example, it can be used on input to parse strings that contain thousands separators and decimal separators. It also can output scientific notation, and there are methods that give you additional control over the formats.

QUESTION 18:

What do you suspect this fragment writes?

int profit = 32876.34;

DecimalFormat numform = new DecimalFormat("$0.00"); 

System.out.println( "profit = " + numform.format(profit) );